package kbpost

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteEntryFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteEntryFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteEntryFavoriteLogic {
	return &DeleteEntryFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteEntryFavoriteLogic) DeleteEntryFavorite(
	req *types.DeleteEntryFavoriteReq,
	headers *[]*types.Header,
) (*types.BaseMsgResp, error) {
	if (req.EntryId == nil || *req.EntryId == 0) && (req.EntryIds == nil || len(strings.TrimSpace(*req.EntryIds)) == 0) {
		return nil, resultx.NewErrCode(resultx.ENTRY_ID_REQUIRED)
	}

	if req.Type == nil || *req.Type == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_TYPE_INVALID)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var ids []uint64
	idMap := make(map[int64]struct{})
	if req.EntryIds != nil && len(strings.TrimSpace(*req.EntryIds)) > 0 {
		entryIds := strings.Split(strings.TrimSpace(*req.EntryIds), ",")
		for _, id := range entryIds {
			if i, err := strconv.ParseInt(id, 10, 64); err == nil && i > 0 {
				if _, ok := idMap[i]; !ok {
					idMap[i] = struct{}{}
					ids = append(ids, uint64(i))
				}
			}
		}
	} else {
		ids = append(ids, *req.EntryId)
	}

	reactionType := util.GetReactionType(*req.Type)

	for _, id := range ids {
		_, err := l.svcCtx.BlogRpc.LogReaction(l.ctx, &blogclient.LogReactionReq{
			PostId:   id,
			PostType: uint32(globalkey.PostTypeKnowledgeBase),
			UserId:   userId,
			Type:     reactionType,
			Status:   uint32(globalkey.StatusDisabled),
		})
		if err != nil {
			return nil, err
		}
	}

	return &types.BaseMsgResp{
		Msg: "操作成功",
	}, nil
}
